module API where
import Foreign
import Foreign.C
import Foreign.C.String
import Foreign.Ptr
import Foreign.ForeignPtr
import Foreign.Marshal.Alloc
import Control.Exception (block)
import Data.List

foreign import ccall "httpsRequest"  httpsRequest :: CString -> CString -> CString


data JSON = Object [(String, JSON)] | List [JSON] | I Integer | F Float | S String deriving (Eq, Ord, Show)
--data JSONList = IL [Integer] | FL [Float] | SL [String] | ObjectL [JSON] | LL [JSONList] deriving Show

queryList = ["world_names.json", "map_names.json", "event_names.json", "events.json", "wvw/matches.json", "wvw/match_details.json?match_id=", "wvw/objective_names.json", "items.json", "item_details.json?item_id=", "recipes.json", "recipe_details.json?recipe_id=", "guild_details.json", "colors.json", "build.json"]

api_server = "api.guildwars2.com"
getServerQuery code = "/v1/" ++ queryList !! code

serverQuery :: String -> String -> IO String
serverQuery [] _ = return "please specify a host to connect"
serverQuery xs [] = newCString xs >>= \a -> newCString "" >>= \b -> peekCString $ httpsRequest a b
serverQuery xs ys = do
			server <- newCString xs
			get <- newCString ys
			peekCString $ httpsRequest server get

printText :: IO String -> IO()
printText a = do
			str <- a
			putStrLn str
	
{-	
consumeSpaces (x:xs) = if x == ' ' || x == '\t' || x == '\n' || x == '\r' || x == ':' || x == ',' then consumeSpaces xs else x:xs
consumeSpaces [] = []
	
parseJson :: String -> Maybe JSON
parseJson xs = start $ consumeSpaces xs where
	start (x:xs)
		|x == '{' = parseObject xs
		|x == '[' = parseList xs
		
parseObject :: String -> Maybe JSON
parseObject xs = case parseTuples xs of
			Just ys -> Just (Object ys)
			otherwise -> Nothing
			where
				parseTuples (x:xs) = 

--parse String --> String to parse --> Tuple := (result, rest)
parseString :: String -> (String, String)
parseString (x:xs) = if x == '\"' then ([], xs) else (x: fst $ parseString xs, snd $ parseString xs)
-}